package chapter8;


import java.util.TreeMap;

class R implements Comparable {
    int count;
    public R(int count) {
        this.count = count;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(obj != null && obj.getClass() == R.class) {
            R r = (R)obj;
            return r.count == this.count;
        }
        return false;
    }

    @Override
    public int compareTo(Object o) {
        R r = (R)o;
        return count > r.count ? 1 : count < r.count ? -1 : 0;
    }

    @Override
    public String toString() {
        return "R{" +
                "count=" + count +
                '}';
    }
}

/**
 * TreeMap内部是红黑树，添加时根据key对节点进行排序，可以使用自然排序和
 * 定制排序规则
 */
public class TreeMapTest {
    public static void main(String[] args) {
        TreeMap tm = new TreeMap();
        tm.put(new R(3), "java");
        tm.put(new R(-5), "python");
        tm.put(new R(9), "nodejs");
        System.out.println(tm);
        System.out.println(tm.firstEntry());
        System.out.println(tm.lastKey());
        System.out.println(tm.higherKey(new R(2)));
        System.out.println(tm.lowerEntry(new R(2)));
        System.out.println(tm.subMap(new R(-1), new R(4)));
    }
}